package com.my.study.aqs;

import com.my.study.utils.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Carlos
 * @version 1.0
 * @Description TODO
 * @date 2021/6/20 18:16
 **/
@Slf4j(topic = "c.TestCyclicBarrier")
public class TestCyclicBarrier {

    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(2);
        CyclicBarrier barrier = new CyclicBarrier(2, () -> {
            log.debug("task1 task2 finish...");
        });

        for (int i = 0; i < 3; i++) {
            service.submit(() -> {
                log.debug("task1 begin...");
                ThreadUtil.sleep(1);
                try {
                    barrier.await(); // 2 - 1 = 1
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
                log.debug("task1 end...");
            });


            service.submit(() -> {
                log.debug("task2 begin...");
                ThreadUtil.sleep(1);
                try {
                    barrier.await(); // 1 - 1 = 0
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
                log.debug("task2 end...");
            });

        }

        service.shutdown();
    }


}
